package cn.com.hatech.blog.module.admin.setting.controller;

import cn.com.hatech.blog.common.constant.LogActions;
import cn.com.hatech.blog.common.constant.WebConst;
import cn.com.hatech.blog.common.controller.BaseController;
import cn.com.hatech.blog.common.exception.TipException;
import cn.com.hatech.blog.common.result.RestResponse;
import cn.com.hatech.blog.common.utils.UserRequest;
import cn.com.hatech.blog.module.admin.dashboard.service.ILogService;
import cn.com.hatech.blog.module.admin.setting.service.IOptionService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @projectName: hatech-blog
 * @package: cn.com.hatech.blog.module.admin.controller
 * @className: SettingController
 * @author: xuruikai
 * @description: 系统配置控制器
 * @date: 2020/1/11 14:27
 * @version: 1.0
 */
@RestController
@RequestMapping("/api/v1/admin/setting")
@Slf4j
public class SettingRestController extends BaseController {

    @Resource
    private IOptionService optionService;

    @Resource
    private ILogService logService;

    /**
     * 保存系统设置
     */
    @PostMapping(value = "")
    @ResponseBody
    @Transactional(rollbackFor = TipException.class)
    public RestResponse saveSetting(@RequestParam(required = false) String siteTheme, HttpServletRequest request) {
        try {
            Map<String, String[]> parameterMap = request.getParameterMap();
            Map<String, String> query = new HashMap<>(1);
            parameterMap.forEach((key, value) -> query.put(key, join(value)));
            optionService.saveOptions(query);
            WebConst.initConfig = query;
            if (StringUtils.isNotEmpty(siteTheme)) {
                BaseController.THEME = "themes/" + siteTheme;
            }
            logService.insertLog(LogActions.SYS_SETTING.getAction(), JSONObject.toJSONString(query), UserRequest.getRemoteAddr(), UserRequest.getCurrentUserId());
            return RestResponse.ok();
        } catch (Exception e) {
            String msg = "保存设置失败";
            if (e instanceof TipException) {
                msg = e.getMessage();
            } else {
                log.error(msg, e);
            }
            return RestResponse.fail(msg);
        }
    }

    /**
     * 数组转字符串
     *
     * @param arr
     * @return
     */
    private String join(String[] arr) {
        StringBuilder ret = new StringBuilder();
        String[] var3 = arr;
        int var4 = arr.length;

        for (int var5 = 0; var5 < var4; ++var5) {
            String item = var3[var5];
            ret.append(',').append(item);
        }
        return ret.length() > 0 ? ret.substring(1) : ret.toString();
    }

}
